﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;

namespace System.Extensions
{
    public static class PrincipalExtensions
    {
        /// <summary>
        /// 用户编号
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static long UserId(this IPrincipal user)
        {
            long.TryParse(GetValue(user, "UserId"), out var userId);
            return userId;
        }

        /// <summary>
        /// 用户名
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static string UserName(this IPrincipal user)
        {
            return GetValue(user, "UserName");
        }

        #region RoleName
        public static string RoleName(this IPrincipal user)
        {
            return GetValue(user, "RoleName");
        }
        #endregion

        #region RoleId
        public static long RoleId(this IPrincipal user)
        {
             long.TryParse(GetValue(user, "RoleId"),out var RoleId) ;
            return RoleId;
        }
        #endregion

        #region private
        private static string GetValue(IPrincipal user, string key)
        {
            if (user.Identity.IsAuthenticated)
            {
                ClaimsIdentity claimsIdentity = user.Identity as ClaimsIdentity;
                var claim = claimsIdentity.Claims.SingleOrDefault(o => o.Type.Equals(key));
                return claim != null ? claim.Value : string.Empty;
            }

            return string.Empty;
        }
        #endregion

       

    }
}
